package util;

import java.sql.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库连接工具类
 */
public class DBUtil {
    // 单例模式
    private DBUtil() {
    }

    private static MysqlDataSource dataSource;
    private static volatile Connection connection;

    private static MysqlDataSource getDataSource() {
        if(dataSource == null) {
            synchronized (DBUtil.class) {
                if(dataSource == null) {
                    dataSource = new MysqlDataSource();
                    dataSource.setURL("jdbc:mysql://43.142.43.237:3306/orderdb2022?characterEncoding=utf8&useSSL=false");
                    //dataSource.setURL("jdbc:mysql://127.0.0.1:3306/orderdb2022?characterEncoding=utf8&useSSL=false");
                    dataSource.setUser("root");
                    //dataSource.setPassword("root");
                    dataSource.setPassword("12345678");
                }
            }
        }
        return dataSource;
    }

    // 1. Connection 对象
    public static Connection getConnection() throws SQLException {
        MysqlDataSource dataSource = getDataSource();
        return dataSource.getConnection();
    }

    // 2. 关闭资源
    public static void close(ResultSet set, PreparedStatement statement, Connection connection) throws SQLException {
        if(set != null) set.close();
        if(statement != null) statement.close();
        if(connection != null) connection.close();
    }
}
